package com.frxuexi.lib_base.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.bean.ApiResponse
import com.frxuexi.lib_base.bean.UiState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.lang.Exception

open class BaseViewModel<T>:ViewModel() {

    private val _uiState=MutableStateFlow<UiState<T>>(UiState(true))
    val uiState:StateFlow<UiState<T>>
        get() = _uiState

    //用于发射UI状态
    fun emitUiState(showLoading:Boolean=false,
                    data:T?=null,
                    error:String?=null,
                    showLoadingMore:Boolean=false,
                    noMoreData:Boolean=false){
        _uiState.value= UiState(showLoading,data,error,showLoadingMore,noMoreData)
    }

    /**
     * 启动协程
     */
    fun launch(tryBlock:suspend CoroutineScope.()->Unit,
               catchBlock:suspend CoroutineScope.()->Unit,
               finallyBlock:suspend CoroutineScope.()->Unit
    ){
        viewModelScope.launch {
            try {
                tryBlock()
            }catch (e:Exception){
                catchBlock()
            }finally {
                finallyBlock()
            }
        }
    }

    /**
     * 请求结果处理
     */
    suspend fun <T> handleRequest(response: ApiResponse<T>,
                                errorBlock: suspend CoroutineScope.(response:ApiResponse<T>)->Boolean={false},
                                  successBlock:suspend CoroutineScope.(response:ApiResponse<T>)->Unit={}){
        coroutineScope {
            when(response.statusCode){
                200->successBlock(response)
                else->{
                    BaseApp.baseViewModel.emitError(response)
                }
            }
        }
    }
}